var httpsUrl = getApp().globalData.httpsUrl;
var globalData = getApp().globalData;
var commonUtil = require("../../../utils/commonUtil.js")
const innerAudioContext = wx.createInnerAudioContext();
Page({
  data: {
    imgUrl: globalData.imgUrl,
    registerFlag:0,// 0不展示授权信息 1展示
    phoneFlag:0,//0不展示手机授权  1展示
    user:[],
    tjList:[],
    rmList:[],
    contents:'欢迎来到愿者上钩~',
    banners:[],
    lat:"",
    lon:"",
    titleOne: "类型",
    titleTwo: "筛选",
    selectListOne: [],
    selectListTwo: ["最新", "最热", "最近"],
    showId: -1,
    businessType: '',//类型id
    titleFlag:1,
  },
  loadData: function () {
    var that = this;
    this.banners();
    this.news();
    this.goodsList();
    this.types();
  },
  goodsList:function() {
    let that = this;
    wx.getLocation({               
      success: function (res) {
        console.log("已获取到经纬度");
        that.setData({ lat: res.latitude})
        that.setData({ lon: res.longitude })
        that.tjg();
        // that.remai();
      },
      fail: function (res) {
        console.log('拒绝获取经纬度');
        that.tjg();
        // that.remai();
      }
    })
  },
  //特价购列表
  tjg: function () {
    var that = this;
    var params = new Object();
    params.pageNo = 1;
    params.pageSize = 20;
    //params.type = 1;//推广类型 1.代金券 2.热卖
    params.lat = this.data.lat;
    params.lon = this.data.lon;
    // if (this.data.businessType.length != '') {
    //   params.businessType = this.data.businessType;
    // }
    let titleTwo = this.data.titleTwo;//1,最新 2,最热 3,最近
    // switch (titleTwo) {
    //   case '最新': params.orderType = 1; break;
    //   case '最热': params.orderType = 2; break;
    //   case '最近': params.orderType = 3; break;
    // }
    params.orderType = this.data.titleFlag;
    let openId = wx.getStorageSync("openidKey");
    console.log("param:" + JSON.stringify(params));
    wx.request({
      header: { "openId": openId, "content-Type": "application/x-www-form-urlencoded" },
      url: httpsUrl + "/goods/getGoodsList",
      dataType: "json",
      method: "GET",
      data: params,
      success: function (res) {
        res = res.data;
        console.log("特价购：" + JSON.stringify(res));
        if (res.result == 0) {
          let rows = res.data.list;
          that.setData({ tjList: rows })
          that.commission(1);
        }
      }
    })
  },
  //商家类型
  types: function () {
    var that = this;
    var params = new Object();
    let openId = wx.getStorageSync("openidKey");
    wx.request({
      header: { "openId": openId, "content-Type": "application/x-www-form-urlencoded" },
      url: httpsUrl + "/business/getBusinessType",
      dataType: "json",
      method: "GET",
      data: params,
      success: function (res) {
        res = res.data;
        console.log("类型：" + JSON.stringify(res));
        if (res.result == 0) {
          let rows = res.data;
          that.setData({ selectListOne: rows })
        }
      }
    })
  },
  //设置显示块id
  showSearch: function (e) {
    let id = e.currentTarget.id;
    if (id == this.data.showId) {
      this.setData({ showId: -1, })
    } else {
      this.setData({ showId: id })
    }
    console.log(this.data.showId)
  },
  //查询条件选择事件
  selectItem: function (e) {
    let text = e.currentTarget.dataset.text;
    let id = e.currentTarget.id;
    if (id == 1) { //text为index,-1为全部
      if (text == '-1') {
        this.setData({ titleOne: '全部', businessType: '' })
      } else {
        let index = Number(text);
        let rows = this.data.selectListOne;
        let name = rows[index].name;
        let typeId = rows[index].id;
        this.setData({ titleOne: name, businessType: typeId, })
      }
    } else if (id == 2) {
      if (text == '-1') {
        this.setData({ titleTwo: '全部' })
      } else {
        this.setData({ titleTwo: text })
      }
    }
    this.setData({ showId: -1 })
    this.tjg();
  },
  //商品显示块id
  titleSelect: function (e) {
    let id = e.currentTarget.id;
    this.setData({
      titleFlag: id,
    })
    this.tjg();
  },
  //特价购列表
  tjg1: function () {
    var that = this;
    var params = new Object();
    params.pageNo = 1;
    params.pageSize = 5;
    params.type = 1;//推广类型 1.代金券 2.热卖
    params.lat = this.data.lat;
    params.lon = this.data.lon;
    let openId = wx.getStorageSync("openidKey");
    wx.request({
      header: { "openId": openId, "content-Type": "application/x-www-form-urlencoded" },
      url: httpsUrl + "/goods/getGoodsPromotion",
      dataType: "json",
      method: "GET",
      data: params,
      success: function (res) {
        res = res.data;
        console.log("特价购：" + JSON.stringify(res));
        if (res.result == 0) {
          let rows = res.data.list;
          that.setData({ tjList: rows })
          that.commission(1);
        }
      }
    })
  },
  //热卖列表
  remai: function () {
    var that = this;
    var params = new Object();
    params.pageNo = 1;
    params.pageSize = 5;
    params.type = 2;//推广类型 1.代金券 2.热卖
    params.lat = this.data.lat;
    params.lon = this.data.lon;
    let openId = wx.getStorageSync("openidKey");
    wx.request({
      header: { "openId": openId, "content-Type": "application/x-www-form-urlencoded" },
      url: httpsUrl + "/goods/getGoodsPromotion",
      dataType: "json",
      method: "GET",
      data: params,
      success: function (res) {
        res = res.data;
        console.log("热卖：" + JSON.stringify(res));
        if (res.result == 0) {
          let rows = res.data.list;
          that.setData({ rmList: rows })
          that.commission(2);
        }
      }
    })
  },
  commission:function(id){
    var that = this;
    let openId = wx.getStorageSync("openidKey");
    let rows = [];
    if(id==1){
      rows = this.data.tjList;
    }else{
      rows = this.data.rmList;
    }
    if (rows != null && rows.length > 0) {
      for (let i = 0; i < rows.length; i++) {
        let row = rows[i];
        wx.request({
          header: { "openId": openId, "content-Type": "application/x-www-form-urlencoded" },
          url: httpsUrl + "/goodsCommission/getCommission",
          dataType: "json",
          method: "POST",
          data: { "goodsNo": rows[i].code},
          success: function (res) {
            res = res.data;
            //console.log(rows[i].code+"佣金：" + JSON.stringify(res));
            if (res.result == 0) {
              row.commissionStr = res.data;
              if (rows[i].promotion_describe == null) { row.promotion_describe=""}
              rows[i] = row;
              if (id == 1) {
                that.setData({ tjList: rows })
              }else{
                that.setData({ rmList: rows })
              }
            }
          }
        })
      }
    }
  },
  //顶部大图
  banners: function () {
    var that = this;
    var params = new Object();
    params.advSite = 1;//广告位置 "1":首页banner大图, "2":首页文字公告, "3":商家页banner大图, "4":海报页banner大图	
    let openId = wx.getStorageSync("openidKey");
    wx.request({
      header: { "openId": openId, "content-Type": "application/x-www-form-urlencoded" },
      url: httpsUrl + "/adver/getPosAdverList",
      dataType: "json",
      method: "GET",
      data: params,
      success: function (res) {
        res = res.data;
        console.log("大图：" + JSON.stringify(res));
        if (res.result == 0) {
          // let rows = res.data;
          that.setData({ banners: res.data})
        }
      }
    })
  },
  //广告跳转 link_type：1,链接到商家首页 2,链接到商品页  link_data：参数code
  bannerGo:function(e){
    let id = e.currentTarget.id;
    let banners = this.data.banners;
    let banner = banners[id];
    if (banner.link_type == 1){
      wx.setStorageSync("businessCode", banner.link_data);
      wx.navigateTo({
        url: '../../shop/shopInfo/shopInfo',
      })
    } else if (banner.link_type == 2) {
      wx.setStorageSync("goodsCode", banner.link_data);
      wx.navigateTo({ url: '../../shop/goodsInfo/goodsInfo', })
    }
  },
  //广告,喇叭
  news: function () {
    var that = this;
    var params = new Object();
    params.advSite = 2;//广告位置 "1":首页banner大图, "2":首页文字公告, "3":商家页banner大图, "4":海报页banner大图	
    let openId = wx.getStorageSync("openidKey");
    wx.request({
      header: { "openId": openId, "content-Type": "application/x-www-form-urlencoded" },
      url: httpsUrl + "/adver/getPosAdverList",
      dataType: "json",
      method: "GET",
      data: params,
      success: function (res) {
        res = res.data;
        //console.log("广告：" + JSON.stringify(res));
        if (res.result == 0) {
          // let rows = res.data;
          that.setData({ contents: res.data[0].adv_content })
        }
      }
    })
  },
  //音频播放
  play:function(){
    let that = this;
    let flag = wx.getStorageSync("yinping");//1：播报  0：不播
    this.setData({ yinping:flag});
    if (flag != '0'){
      that.bofang();
    }
  },
  //停止播放
  stop: function () {
    innerAudioContext.pause();
    wx.setStorageSync("yinping", '0');
    this.setData({ yinping: '0' });
  },
  bofang:function(){
    wx.setStorageSync("yinping", '1');
    this.setData({ yinping: '1' });
    let that = this;
    let openId = wx.getStorageSync("openidKey");
    wx.request({
      header: { "openId": openId },
      url: httpsUrl + "/business/getAgentBoradCast",
      dataType: "json",
      method: "GET",
      // data: params,
      success: function (result) {
        console.log("广播："+JSON.stringify(result));
        var res = result.data;
        if (res.result == 0) {
          // innerAudioContext.src = "https://iotng.58shareiot.com/yzsg-xcx-img/ban.mp3";
          innerAudioContext.src = res.data;
          innerAudioContext.play();
        }
      }
    })
  },

  onLoad: function (options) {
    console.log("options:" + JSON.stringify(options));
    const scene = decodeURIComponent(options.scene);//小程序码携带参数
    console.log("scene:" + scene);
    if (scene != undefined && scene != 'undefined' && scene.length > 0) {
      wx.setStorageSync("parentCode", scene);//扫用户码进入则有此code
    }
    this.getOpenId();
  },

  onShow: function () {
    this.loadData();
  },
  onShareAppMessage: function () {
  },
  //用户信息检验,若不存在，则授权,若已存在判断手机号
  getOpenId:function(){
    let that = this;
    wx.login({
      success: function (res) {
        wx.showLoading({title: '请稍等...',})
        wx.request({
          header: {"content-Type": "application/x-www-form-urlencoded" },
          url: httpsUrl + "/wechat/getOpenId", 
          dataType: "json",
          method: "POST",
          data: { "code": res.code, "agentCode": globalData.agentCode},
          success: function (res) {
            wx.hideLoading();
            res = res.data;
            console.log("获取openid返回:" + JSON.stringify(res));
            if (res.result == 0) {
              let data = JSON.parse(res.data);
              wx.setStorageSync("openidKey", data.openid);
              wx.setStorageSync("sessionKey", data.session_key);
              console.log("openid:" + data.openid);
              that.searchUser();
              //that.loadData();
            } else {
              console.log("获取openid失败：" + res.msg);
            }
          }
        })
      }
    })
  },
  //查询用户信息
  searchUser:function(){
    let that = this;
    let openId = wx.getStorageSync("openidKey");
    wx.request({
      header: { "openId": openId, "content-Type": "application/x-www-form-urlencoded" },
      url: httpsUrl + "/member/info",
      dataType: "json",
      method: "GET",
      // data: { "openId": data.openid },
      success: function (res) {
        res = res.data;
        console.log("userInfo:" + JSON.stringify(res));
        if (res.result == 0) {
          var user = res.data;
          that.setData({ user: user })
          if (commonUtil.isEmpty(user.phone)) {
            that.setData({ phoneFlag: 1 })
          }else{
            commonUtil.openXcx();
            that.play();
          }
          that.loadData();
        } else if (res.result == 2) {
          that.setData({ registerFlag: 1 })//{"result":2,"msg":"用户未注册!","data":null}
        }
      }
    })
  },
  //授权信息
  getUserInfo: function (e) {
    var that = this;
    //会弹框询问是否授权，拒绝则得到undefined
    //console.log("wxinfo:" + JSON.stringify(e.detail.userInfo));
    let info = e.detail.userInfo;
    if (!commonUtil.isEmpty(info)) {
      var params = new Object();
      params.openId = wx.getStorageSync("openidKey");
      params.nick = info.nickName;
      params.sex = info.gender;//性别 1 男，2 女，0未知
      params.img = info.avatarUrl;//头像
      params.country = info.country;
      params.provice = info.province;
      params.city = info.city;
      // params.unionId = this.data.unionId;
      params.agentCode = globalData.agentCode;//代理商编码，小程序固定值
      params.parentCode = wx.getStorageSync("parentCode");//推荐用户编码
      //params.businessCode = wx.getStorageSync("businessCode");//商家编码
      console.log("params:" + JSON.stringify(params));
      commonUtil.showLoading("请稍等...");
      wx.request({
        // header: {"content-Type": "application/x-www-form-urlencoded" },
        url: httpsUrl + "/regist?parentCode=" + params.parentCode,
        dataType: "json",
        method: "POST",
        data: params,
        success: function (result) {
          commonUtil.hideLoading();
          var res = result.data;
          console.log("注册返回：" + JSON.stringify(res));
          if (res.result == 0) {
            commonUtil.showSuccessToast("注册成功");
            that.setData({ registerFlag: 0 })
            that.searchUser();
          } else {
            commonUtil.showModal("注册失败！" + res.message);
          }
        }
      })
    }
  },
  //手机号授权获取
  getphonenumber: function (e) {
    this.setData({ phoneFlag: 0 })
    //console.log("encryptedData:" + JSON.stringify(e.detail.encryptedData));
    if (commonUtil.isEmpty(e.detail.encryptedData)) {
      return;
    }
    let that = this;
    var params = new Object();
    params.encryptedData = e.detail.encryptedData;
    params.iv = e.detail.iv;
    // params.code = wx.getStorageSync("code");
    params.sessionKey = wx.getStorageSync("sessionKey");
    console.log("手机解密参数：" + JSON.stringify(params));
    wx.request({
      header: {"content-Type": "application/x-www-form-urlencoded" },
      url: httpsUrl + "/wechat/xcxUserPhone",
      dataType: "json",
      method: "GET",
      data: params,
      success: function (result) {
        var res = result.data;
        console.log("解密结果：" + JSON.stringify(res));
        if (res.result == 0) {
          let data = JSON.parse(res.data);
          let phone = data.phoneNumber;
          console.log(phone);
          commonUtil.updatePhoneByWechat(phone);
          that.loadData();
        }
      }
    })
  },
  

  formId: function (e) {
    let formId = e.detail.formId;
    let id = e.currentTarget.id;
    if (formId.indexOf("formId") == -1) {//非真机上是the formId is a mock one
      console.log("formId:" + formId);
      let that = this;
      var params = new Object();
      params.formId = formId;
      let openId = wx.getStorageSync("openidKey");
      wx.request({
        header: { "openId": openId, "content-Type": "application/x-www-form-urlencoded" },
        url: httpsUrl + "/message/add",
        dataType: "json",
        method: "POST",
        data: params,
        success: function (res) {
          var str = res.data;
          console.log("save_formid:" + JSON.stringify(res));
        }
      })
    }
    if (id == 1){
      wx.navigateTo({ url: '../memberCard/memberCard', })
    } else if (id == 2) {
      wx.navigateTo({ url: '../voucher/voucher', })
    } else if (id == 3) {
      wx.navigateTo({ url: '../offersList/offersList', })
    } else if (id == 4) {
      wx.navigateTo({ url: '../myCode/myCode', })
    } else if (id == 5) {
      wx.navigateTo({ url: '../makeMoneyNote/makeMoneyNote', })
    }
  },
  offersList: function () {
    wx.navigateTo({ url: '../offersList/offersList', })
  },
  discountCardGoods: function () {
    wx.navigateTo({ url: '../discountCardGoods/discountCardGoods', })
  },
  myCode: function () {
    wx.navigateTo({ url: '../myCode/myCode', })
  },
  voucher: function () {
    wx.navigateTo({ url: '../voucher/voucher', })
  },
  memberCard: function () {
    wx.navigateTo({ url: '../memberCard/memberCard', })
  },
  poster: function () {
    wx.navigateTo({ url: '../poster/poster', })
  },
  goodsInfo: function (e) {
    let id = e.currentTarget.id;
    wx.setStorageSync("goodsCode", id);
    wx.navigateTo({ url: '../../shop/goodsInfo/goodsInfo', })
  },
  makeMoneyNote: function () {
    wx.navigateTo({ url: '../makeMoneyNote/makeMoneyNote', })
  },
})